import React from 'react';
import routes from './routes';
import { useSelector } from 'react-redux';
import { useNavigate,useLocation, Navigate, Routes,Route } from 'react-router-dom';
import { Suspense } from 'react';

const isCheckLogin = (path,tk)=>{
    let checkList = ['/','/user'];
    return !tk && checkList.includes(path);
}

const Element = function Element(props){
    let {component:Component,path,meta} = props;
    let {tk} = useSelector(state=>state.base);
    // 检查是否登录，没有登录，需要跳转到登录页面
    let isLogin = !isCheckLogin(path,tk);
    let {title = '首页'} = meta || {}
    document.title = title

    const navigate = useNavigate();
    const location = useLocation();

    // 根据条件渲染组件
    return <>
    {(isLogin || tk) ? 
    <Component navigate = {navigate} location = {location} /> 
    :<Navigate replace = {true} to = {'/login'} state = {{from: `${location.pathname}`}}/>}
    </>

}

export default function RouterView(){
    return <Suspense>
        <Routes>
            {routes.map(item=>{
                let { path,name } = item;
                return  <Route key={name} path={path} element={<Element {...item} />}></Route>
            })}
        </Routes>
    </Suspense>
}